import React, { useState, useEffect, useRef } from 'react'
import { Toast, SpinLoading, Popup, TextArea, Button, List, Empty } from 'antd-mobile'
import { HeartOutline, MessageOutline } from 'antd-mobile-icons'
import { getVideoCategories, getVideoList, addVideoComment, getVideoCommentList, type VideoItem, type VideoCategory, type VideoCommentItem } from '../../api/video'
import './index.css'

const Cases: React.FC = () => {
  const [categories, setCategories] = useState<VideoCategory[]>([])
  const [videos, setVideos] = useState<VideoItem[]>([])
  const [currentVideoIndex, setCurrentVideoIndex] = useState(0)
  const [loading, setLoading] = useState(false)
  const [currentCategoryId, setCurrentCategoryId] = useState<number | null>(null)
  const [collectionLoading, setCollectionLoading] = useState<{ [key: number]: boolean }>({})
  const [videoLoading, setVideoLoading] = useState<{ [key: number]: boolean }>({})
  const [videoErrors, setVideoErrors] = useState<{ [key: number]: boolean }>({})
  const [videoPlayed, setVideoPlayed] = useState<{ [key: number]: boolean }>({})
  const [commentVisible, setCommentVisible] = useState(false)
  const [commentText, setCommentText] = useState('')
  const [submitting, setSubmitting] = useState(false)
  const [commentLoading, setCommentLoading] = useState(false)
  const [comments, setComments] = useState<VideoCommentItem[]>([])
  
  const videoRefs = useRef<(HTMLVideoElement | null)[]>([])
  const containerRef = useRef<HTMLDivElement>(null)
  const isScrolling = useRef(false)
  const wheelTimeout = useRef<number | null>(null)

  // 获取视频分类
  const fetchCategories = async () => {
    try {
      const response = await getVideoCategories()
      if (response.status === '0000') {
        setCategories(response.result)
        // 默认选择第一个分类
        if (response.result.length > 0) {
          setCurrentCategoryId(response.result[0].id)
          fetchVideos(response.result[0].id)
        }
      }
    } catch (error) {
      console.error('获取视频分类失败:', error)
      Toast.show({ content: '获取视频分类失败' })
    }
  }

  // 获取视频列表
  const fetchVideos = async (categoryId: number) => {
    setLoading(true)
    try {
      const response = await getVideoList(categoryId, 1, 20)
      if (response.status === '0000') {
        setVideos(response.result)
        setCurrentVideoIndex(0)
      }
    } catch (error) {
      console.error('获取视频列表失败:', error)
      Toast.show({ content: '获取视频列表失败' })
    } finally {
      setLoading(false)
    }
  }

  // 切换分类
  const handleCategoryChange = (categoryId: number) => {
    setCurrentCategoryId(categoryId)
    fetchVideos(categoryId)
  }

  // 处理收藏
  const handleCollection = async (video: VideoItem) => {
    if (collectionLoading[video.id]) return
    
    setCollectionLoading(prev => ({ ...prev, [video.id]: true }))
    
    try {
      // 这里可以调用收藏API
      Toast.show({
        content: video.whetherCollection === 1 ? '取消收藏成功' : '收藏成功',
        position: 'center',
      })
      
      // 更新本地状态
      setVideos(prev => prev.map(item => 
        item.id === video.id 
          ? { ...item, whetherCollection: item.whetherCollection === 1 ? 0 : 1 }
          : item
      ))
    } catch (error) {
      Toast.show({ content: '操作失败，请重试' })
    } finally {
      setCollectionLoading(prev => ({ ...prev, [video.id]: false }))
    }
  }

  // 处理视频播放
  const handleVideoPlay = (index: number) => {
    // 暂停其他视频
    videoRefs.current.forEach((video, i) => {
      if (video && i !== index) {
        video.pause()
      }
    })
    
    // 播放当前视频
    const currentVideo = videoRefs.current[index]
    if (currentVideo) {
      currentVideo.play().then(() => {
        setVideoPlayed(prev => ({ ...prev, [index]: true }))
      }).catch(error => {
        console.log('视频播放失败:', error)
        setVideoErrors(prev => ({ ...prev, [index]: true }))
      })
    }
  }

  // 处理视频暂停
  const handleVideoPause = (index: number) => {
    const video = videoRefs.current[index]
    if (video) {
      video.pause()
    }
  }

  // 处理视频加载开始
  const handleVideoLoadStart = (index: number) => {
    setVideoLoading(prev => ({ ...prev, [index]: true }))
    setVideoErrors(prev => ({ ...prev, [index]: false }))
  }

  // 处理视频加载完成
  const handleVideoLoadedData = (index: number) => {
    setVideoLoading(prev => ({ ...prev, [index]: false }))
  }

  // 处理视频加载错误
  const handleVideoError = (index: number) => {
    setVideoLoading(prev => ({ ...prev, [index]: false }))
    setVideoErrors(prev => ({ ...prev, [index]: true }))
    Toast.show({ content: '视频加载失败' })
  }

  // 处理触摸开始
  const handleTouchStart = (e: React.TouchEvent) => {
    isScrolling.current = false
    const touch = e.touches[0]
    if (touch) {
      // 记录起始位置
      const startY = touch.clientY
      const startTime = Date.now()
      
      // 存储触摸信息
      e.currentTarget.setAttribute('data-start-y', startY.toString())
      e.currentTarget.setAttribute('data-start-time', startTime.toString())
    }
  }

  // 处理触摸移动
  const handleTouchMove = (e: React.TouchEvent) => {
    isScrolling.current = true
  }

  // 处理触摸结束
  const handleTouchEnd = (e: React.TouchEvent) => {
    if (!isScrolling.current) return
    
    const touch = e.changedTouches[0]
    const startY = parseFloat(e.currentTarget.getAttribute('data-start-y') || '0')
    const startTime = parseInt(e.currentTarget.getAttribute('data-start-time') || '0')
    const endY = touch.clientY
    const endTime = Date.now()
    const diffY = startY - endY
    const diffTime = endTime - startTime
    
    // 判断滑动方向和距离，以及滑动速度
    const minDistance = 50
    const maxTime = 500 // 最大滑动时间（毫秒）
    
    if (Math.abs(diffY) > minDistance && diffTime < maxTime) {
      if (diffY > 0 && currentVideoIndex < videos.length - 1) {
        // 向上滑动，切换到下一个视频
        setCurrentVideoIndex(prev => prev + 1)
      } else if (diffY < 0 && currentVideoIndex > 0) {
        // 向下滑动，切换到上一个视频
        setCurrentVideoIndex(prev => prev - 1)
      }
    }
    
    // 清除触摸信息
    e.currentTarget.removeAttribute('data-start-y')
    e.currentTarget.removeAttribute('data-start-time')
  }

  // 处理鼠标滚轮事件
  const handleWheel = (e: React.WheelEvent) => {
    e.preventDefault() // 阻止默认滚动行为
    
    // 清除之前的定时器
    if (wheelTimeout.current) {
      clearTimeout(wheelTimeout.current)
    }
    
    const deltaY = e.deltaY
    const threshold = 50 // 滚轮阈值
    
    // 防止快速滚动，添加防抖
    if (Math.abs(deltaY) > threshold) {
      wheelTimeout.current = setTimeout(() => {
        if (deltaY > 0 && currentVideoIndex < videos.length - 1) {
          // 向下滚动，切换到下一个视频
          setCurrentVideoIndex(prev => prev + 1)
        } else if (deltaY < 0 && currentVideoIndex > 0) {
          // 向上滚动，切换到上一个视频
          setCurrentVideoIndex(prev => prev - 1)
        }
      }, 100) // 100ms 防抖延迟
    }
  }

  // 格式化时长
  const formatDuration = (seconds: number) => {
    const minutes = Math.floor(seconds / 60)
    const remainingSeconds = seconds % 60
    return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`
  }

  // 打开评论输入
  const openComment = async () => {
    setCommentText('')
    setCommentVisible(true)
    // 拉取评论列表
    const current = videos[currentVideoIndex]
    if (!current) return
    setCommentLoading(true)
    try {
      const res = await getVideoCommentList(current.id)
      if (res.status === '0000') {
        setComments(res.result || [])
      } else {
        setComments([])
      }
    } catch (e) {
      setComments([])
    } finally {
      setCommentLoading(false)
    }
  }

  // 提交评论
  const submitComment = async () => {
    if (!videos[currentVideoIndex]) return
    const content = commentText.trim()
    if (!content) {
      Toast.show({ content: '请输入评论内容' })
      return
    }
    setSubmitting(true)
    try {
      const res = await addVideoComment(videos[currentVideoIndex].id, content)
      if (res.status === '0000' || res.status === '9001') {
        Toast.show({ content: res.message || '评论成功' })
        setCommentVisible(false)
        setCommentText('')
      } else {
        Toast.show({ content: res.message || '评论失败' })
      }
    } catch (e) {
      Toast.show({ content: '网络错误，请稍后重试' })
    } finally {
      setSubmitting(false)
    }
  }

  // 组件挂载时获取数据
  useEffect(() => {
    fetchCategories()
    
    // 清理函数
    return () => {
      if (wheelTimeout.current) {
        clearTimeout(wheelTimeout.current)
      }
    }
  }, [])

  // 当前视频变化时自动播放
  useEffect(() => {
    if (videos.length > 0 && currentVideoIndex >= 0 && currentVideoIndex < videos.length) {
      // 延迟播放，等待DOM更新
      setTimeout(() => {
        const currentVideo = videoRefs.current[currentVideoIndex]
        if (currentVideo) {
          // 先暂停其他视频
          videoRefs.current.forEach((video, i) => {
            if (video && i !== currentVideoIndex) {
              video.pause()
            }
          })
          
          // 尝试播放当前视频，如果失败则显示播放按钮
          currentVideo.play().catch(error => {
            console.log('视频自动播放被阻止，需要用户交互:', error)
            // 不设置错误状态，只是不自动播放
          })
        }
      }, 100)
    }
  }, [currentVideoIndex, videos])

  if (loading && videos.length === 0) {
    return (
      <div className="cases-loading">
        <SpinLoading color="primary" />
        <p>加载中...</p>
      </div>
    )
  }

  return (
    <div className="cases-page">
      {/* 分类标签 */}
      {categories.length > 0 && (
        <div className="category-tabs">
          {categories.map((category) => (
            <div
              key={category.id}
              className={`category-tab ${currentCategoryId === category.id ? 'active' : ''}`}
              onClick={() => handleCategoryChange(category.id)}
            >
              {category.name}
            </div>
          ))}
        </div>
      )}

      {/* 视频容器 */}
      <div 
        className="video-container"
        ref={containerRef}
        onTouchStart={handleTouchStart}
        onTouchMove={handleTouchMove}
        onTouchEnd={handleTouchEnd}
        onWheel={handleWheel}
      >
        {videos.length > 0 ? (
          <div 
            className="video-wrapper"
            style={{ transform: `translateY(-${currentVideoIndex * 100}vh)` }}
          >
            {videos.map((video, index) => (
              <div key={video.id} className="video-item">
                                 {/* 视频播放器 */}
                 <video
                   ref={(el) => (videoRefs.current[index] = el)}
                   className="video-player"
                   src={video.shearUrl || video.originalUrl}
                   poster=""
                   loop
                   muted={index !== currentVideoIndex}
                   playsInline
                   onPlay={() => handleVideoPlay(index)}
                   onPause={() => handleVideoPause(index)}
                   onLoadStart={() => handleVideoLoadStart(index)}
                   onLoadedData={() => handleVideoLoadedData(index)}
                   onError={() => handleVideoError(index)}
                   onClick={() => {
                     if (!videoPlayed[index]) {
                       const video = videoRefs.current[index]
                       if (video) {
                         video.play().then(() => {
                           setVideoPlayed(prev => ({ ...prev, [index]: true }))
                         }).catch(() => {
                           // 静默处理错误
                         })
                       }
                     }
                   }}
                 />
                
                {/* 视频加载状态 */}
                {videoLoading[index] && (
                  <div className="video-loading-overlay">
                    <SpinLoading color="primary" />
                    <p>视频加载中...</p>
                  </div>
                )}
                
                {/* 视频错误状态 */}
                {videoErrors[index] && (
                  <div className="video-error-overlay">
                    <div className="error-icon">⚠️</div>
                    <p>视频加载失败</p>
                    <button 
                      className="retry-button"
                      onClick={() => {
                        setVideoErrors(prev => ({ ...prev, [index]: false }))
                        const video = videoRefs.current[index]
                        if (video) {
                          video.load()
                        }
                      }}
                    >
                      重试
                    </button>
                  </div>
                )}
                
                {/* 视频信息覆盖层 */}
                <div className="video-overlay">
                  {/* 右侧操作按钮 */}
                  <div className="video-actions-right">
                    <div className="action-item" onClick={() => handleCollection(video)}>
                      <div className="action-icon">
                        <HeartOutline className={video.whetherCollection === 1 ? 'active' : ''} />
                      </div>
                      <span className="action-text">收藏</span>
                    </div>
                    <div className="action-item" onClick={openComment}>
                      <div className="action-icon">
                        <MessageOutline />
                      </div>
                      <span className="action-text">评论</span>
                    </div>
                    <div className="action-item">
                      <div className="action-icon">
                        <MessageOutline />
                      </div>
                      <span className="action-text">分享</span>
                    </div>
                  </div>

                  {/* 左侧视频信息 */}
                  <div className="video-info">
                    <h3 className="video-title">{video.title}</h3>
                    <p className="video-abstract">{video.abstracts}</p>
                    <div className="video-meta">
                      <span className="video-duration">{formatDuration(video.duration)}</span>
                      {video.price > 0 && (
                        <span className="video-price">{video.price} H币</span>
                      )}
                      <span className="video-buys">购买 {video.buyNum}</span>
                    </div>
                  </div>

                  {/* 底部进度指示器 */}
                  <div className="video-progress">
                    {videos.map((_, i) => (
                      <div
                        key={i}
                        className={`progress-dot ${i === currentVideoIndex ? 'active' : ''}`}
                      />
                    ))}
                  </div>
                </div>

                {/* 播放按钮 */}
                {(index !== currentVideoIndex || !videoPlayed[index]) && (
                  <div className="play-button" onClick={() => {
                    if (index !== currentVideoIndex) {
                      setCurrentVideoIndex(index)
                    } else {
                      // 点击播放当前视频
                      const video = videoRefs.current[index]
                      if (video) {
                        video.play().then(() => {
                          setVideoPlayed(prev => ({ ...prev, [index]: true }))
                        }).catch(error => {
                          console.log('视频播放失败:', error)
                        })
                      }
                    }
                  }}>
                    ▶
                  </div>
                )}
              </div>
            ))}
          </div>
        ) : (
          <div className="video-empty">
            <p>暂无患者案例视频</p>
          </div>
        )}
      </div>
      {/* 评论弹窗 */}
      <Popup
        visible={commentVisible}
        onMaskClick={() => setCommentVisible(false)}
        bodyStyle={{ padding: 12, borderTopLeftRadius: 12, borderTopRightRadius: 12 }}
      >
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          <div style={{ maxHeight: '50vh', overflow: 'auto' }}>
            {commentLoading ? (
              <div style={{ textAlign: 'center', padding: 16 }}>
                <SpinLoading color='primary' />
              </div>
            ) : comments.length === 0 ? (
              <Empty description='暂无评论' />
            ) : (
              <List>
                {comments.map((c) => (
                  <List.Item key={c.id}>{c.content}</List.Item>
                ))}
              </List>
            )}
          </div>
          <div>
            <TextArea
              value={commentText}
              onChange={setCommentText}
              placeholder='说点什么吧…'
              maxLength={60}
              rows={3}
              showCount
            />
            <Button block color='primary' loading={submitting} onClick={submitComment} style={{ marginTop: 8 }}>发表</Button>
          </div>
        </div>
      </Popup>
    </div>
  )
}

export default Cases
